using EmployeeApi.DB;
using Microsoft.EntityFrameworkCore;

namespace EmployeeApi.Interfaces;

public class Repository<T> : IRepository<T> where T : class
{
    private readonly ApiDbContext _db;
    private readonly DbSet<T> _tb;
    public Repository(ApiDbContext db)
    {
        _db = db;
        _tb = _db.Set<T>();
    }

    public async Task<List<T>> GetAllAsync()
    {
        var list = await _tb.ToListAsync();
        return list;
    }
    public async Task<T?> GetByIdAsync(int id)
    {
        var obj = await _tb.FindAsync(id);
        return obj;
    }
    public async Task<T> AddAsync(T entity)
    {
        await _tb.AddAsync(entity);
        await _db.SaveChangesAsync();
        return entity;
    }
    public async Task UpdateAsync(T entity)
    {
        _tb.Update(entity);
        await _db.SaveChangesAsync();
    }
    public async Task DeleteAsync(T entity)
    {
        _tb.Remove(entity);
        await _db.SaveChangesAsync();
    }

}